#include "led.h"
#include "code.h"
#include "oled.h"
#include "delay.h"
void LED_Init(void)
{

    GPIO_InitTypeDef GPIO_InitStructure;
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOC, &GPIO_InitStructure);

    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

    TIM_TimeBaseStructure.TIM_Period = 99;
    TIM_TimeBaseStructure.TIM_Prescaler = 71;
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);

    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    TIM_Cmd(TIM3, ENABLE);
}

int TIM3_cnt0 = 0, TIM3_cnt1 = 0, TIM3_cnt2 = 0;
int overtime = 0;
int pwm_val = 0;
int pwm_set = 0;
static int LED_val = 0;
static int Sleep_time = 10;
void TIM3_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
    {
        TIM3_cnt0++;
        TIM3_cnt2++;
        if (CODE.mode == lock)
        {
            if (TIM3_cnt0 > pwm_set)
                LED = LED_val;
            else
                LED = !LED_val;
        }
        else if (CODE.mode == unlock)
        {
            if (TIM3_cnt0 == 100)
            {
                TIM3_cnt1++;
                if (TIM3_cnt1 == 10)
                {
                    TIM3_cnt1 = 0;
                    LED_val = !LED_val;
                    LED = LED_val;
                }
            }
        }
        if (TIM3_cnt0 == 100)
        {
            if (pwm_val == 0)
            {
                pwm_set++;
            }
            else
            {
                pwm_set--;
            }
            if (pwm_set == 99)
                pwm_val = 1;
            else if (pwm_set == 1)
                pwm_val = 0;
            TIM3_cnt0 = 0;
        }

        if (TIM3_cnt2 >= 10000 * Sleep_time && CODE.mode == unlock && CODE.opera_mode != change_CODE1 && CODE.opera_mode != change_CODE2 && CODE.opera_mode != change_CODE3)
        {
            CODE.mode = lock;
            TIM3_cnt2 = 0;
            overtime = 1;
        }
        TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
    }
}
